using Core.SimpleTemp.Application.YH;
using Core.SimpleTemp.Common;
using Core.SimpleTemp.Common.PagingQuery;
using Core.SimpleTemp.Entitys;
using Core.SimpleTemp.Repositories;
using Core.SimpleTemp.Repositories.Internal;
using Core.Toolkit.Common;
using Core.Toolkit.Core;
using Core.Toolkit.Core.Api;
using Core.Toolkit.Core.Application;
using Core.Toolkit.Core.Model;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Core.SimpleTemp.Application
{
    /// <summary>
    /// 隐患_隐患台账
    /// </summary>
    [AutoDi()]
    public class YH_StandingBookService : BaseAppService<YH_StandingBookDto, YH_StandingBook, YH_StandingBookRepository>
    {
        readonly ExcelHelp _excelHelp;
        readonly UserIdentity _userIdentity;
        readonly CoreDBContext _dbContext;
        readonly WrkerRelationsService _wrker;
        readonly YHService _yHService;
        public YH_StandingBookService(YH_StandingBookRepository repository, ExcelHelp excelHelp, YHService yHService, WrkerRelationsService wrker, IHttpContextAccessor accessor, CoreDBContext dbContext) : base(repository)
        {
            _excelHelp = excelHelp;
            _userIdentity = accessor?.HttpContext?.User?.GetUserIdentity();
            _dbContext = dbContext;
            _wrker = wrker;
            _yHService = yHService;
        }



        private LoadPageOffsetModel<YH_StandingBook, YH_StandingBookDto> GetLoadPageOffsetMode(PagingModel<YH_StandingBookDto> pagingQueryModel)
        {
            var loadPageOffsetModel = this.GetLoadPageOffsetModel(pagingQueryModel);
            var baseQuery = _repository.QueryBase().AsNoTracking();

            var dtoModel = pagingQueryModel.Model;

            var filterList = this.CreateQRList()
.Add("RiskRegion", "=") //
.Add("RiskPosition", "=") //
.Add("OrganizationType", "=") //
.Add("InspectType", "=") //
.Add("RiskType", "=") //
.Add("RiskLevel", "=") //
.Add("Department", "=") //
.Add("RectificationLeading", "=") //
.Add("State", "=") //
 .Add("DiscoveryTime", ">=", DateTimeFormat.getTime(pagingQueryModel.Model.TimeBegin, "b"))
    .Add("DiscoveryTime", "<", DateTimeFormat.getTime(pagingQueryModel.Model.TimeEnd, "e"));









            //工厂处理
            if (_userIdentity.Headoffice)
                filterList.Add("CreateFactory", "="); //总部从查询条件取工厂id
            else
                filterList.Add("CreateFactory", "=", _userIdentity.Factory);

            var filterExpre = filterList.BuildeQR(dtoModel.ToEntity<YH_StandingBook>());

            loadPageOffsetModel.QueryWhere = filterExpre;

            //   .Add("DiscoveryTime", "=") //隐患发现时间
            //.Add("InspectType", "=") //检查类别
            //.Add("RiskRegion", "=") //隐患所属区域
            //.Add("RiskType", "=") //隐患分类
            //.Add("RiskLevel", "=") //隐患等级ID
            //.Add("Schedule", "=") //隐患进度(/待审批/已生效/审批退回/验收通过/验收退回)





            //.Add("Type", "="); //上报分类(计划/0非计划/外部机构)
            //.Add("ScreeningPlanProDetailId", "=") //隐患计划排查明细ID
            //.Add("InstitutionTypes", "=") //机构类别
            //.Add("CompanyName", "=") //单位名称
            //.Add("Discoverer", "=") //发现人
            //.Add("Monitor", "=") //带班长
            //.Add("ApprovalOpinion", "=") //带班长审批意见
            //.Add("ApprovalDate", "=") //带班长审批时间
            //.Add("OrganizationType", "=") //组织类别

            //.Add("RiskPosition", "=") //隐患位置
            //.Add("RiskDescription", "=") //隐患描述
            //.Add("IsMajor", "=") //是否为重大隐患
            //.Add("HaveContractor", "=") //
            //.Add("Contractor", "=") //
            //.Add("RectificationCase", "=") //承包商名称ID
            //.Add("RectificationFund", "=") //整改资金
            //.Add("Department", "=") //整改责任部门
            //.Add("RectificationLeading", "=") //整改责任人
            //.Add("Rectificationer", "=") //整改人
            //.Add("PlanTime", "=") //计划完成时间
            //.Add("HaveContingencyPlan", "=") //是否制定应急预案
            //.Add("EmergencyPlan", "=") //应急预案内容
            //.Add("CurrentPlan", "=") //当前控制措施
            //.Add("RectificationDescription", "=") //整改描述
            //.Add("ActualTime", "=") //实际完成时间
            //.Add("Acceptancer", "=") //指定验收人
            //.Add("ApprovalResult", "=") //验收意见
            //.Add("AppointDepartment", "=") //验收部门
            //.Add("AppointPerson", "=") //验收用户
            //.Add("AppointTime", "=") //验收时间
            //.Add("Status", "=") //状态(保存/提交)
            //.Add("CreateFactory", "=") //隶属工厂
            //.Add("CreateDept", "=") //
            //.Add("UpdateDept", "=");//


            loadPageOffsetModel.BasqQuery = baseQuery;
            var orderModel = new List<OrderModel>()
            {
                new OrderModel(){ IsDesc=true,PropertyName="CreateTime"}
            };

            //列表类型(1台账管理，2整改负责人，3整改人，4验收人)
            switch (pagingQueryModel.Model.Type)
            {
                case "2":
                    baseQuery = baseQuery.Where(a => a.RectificationLeading == pagingQueryModel.Model.RectificationLeading);
                    orderModel = new List<OrderModel>()
                    {
                        new OrderModel(){   IsDesc =false,PropertyName="State"  },
                        new OrderModel(){   IsDesc =true,PropertyName="DiscoveryTime"  }
                    };
                    break;   //整改负责人
                case "3":
                    baseQuery = baseQuery.Where(a => a.Rectificationer == pagingQueryModel.Model.Rectificationer);
                    orderModel = new List<OrderModel>()
                    {
                        new OrderModel(){   IsDesc =false,PropertyName="State"  },
                        new OrderModel(){   IsDesc =true,PropertyName="DiscoveryTime"  }
                    };
                    break;         //整改人列表
                case "4":
                    baseQuery = baseQuery.Where(a => a.State == "未验收" || a.State == "验收通过");
                    orderModel = new List<OrderModel>()
                    {
                        new OrderModel(){   IsDesc =false,PropertyName="State"  },
                        new OrderModel(){   IsDesc =true,PropertyName="ActualTime"  }
                    };
                    break;//验收人
                default: break;
            }
            loadPageOffsetModel.OrderList = orderModel;
            //loadPageOffsetModel.Selector = model => new YH_StandingBook()
            //{
            //            Id = model.Id,
            //Type = model.Type//上报分类(计划/0非计划/外部机构),
            //ScreeningPlanProDetailId = model.ScreeningPlanProDetailId//隐患计划排查明细ID,
            //InstitutionTypes = model.InstitutionTypes//机构类别,
            //CompanyName = model.CompanyName//单位名称,
            //Discoverer = model.Discoverer//发现人,
            //Monitor = model.Monitor//带班长,
            //ApprovalOpinion = model.ApprovalOpinion//带班长审批意见,
            //ApprovalDate = model.ApprovalDate//带班长审批时间,
            //OrganizationType = model.OrganizationType//组织类别,
            //DiscoveryTime = model.DiscoveryTime//隐患发现时间,
            //InspectType = model.InspectType//检查类别,
            //RiskRegion = model.RiskRegion//隐患所属区域,
            //RiskPosition = model.RiskPosition//隐患位置,
            //RiskType = model.RiskType//隐患分类,
            //RiskLevel = model.RiskLevel//隐患等级ID,
            //RiskDescription = model.RiskDescription//隐患描述,
            //IsMajor = model.IsMajor//是否为重大隐患,
            //HaveContractor = model.HaveContractor//,
            //Contractor = model.Contractor//,
            //RectificationCase = model.RectificationCase//承包商名称ID,
            //RectificationFund = model.RectificationFund//整改资金,
            //Department = model.Department//整改责任部门,
            //RectificationLeading = model.RectificationLeading//整改责任人,
            //Rectificationer = model.Rectificationer//整改人,
            //PlanTime = model.PlanTime//计划完成时间,
            //HaveContingencyPlan = model.HaveContingencyPlan//是否制定应急预案,
            //EmergencyPlan = model.EmergencyPlan//应急预案内容,
            //CurrentPlan = model.CurrentPlan//当前控制措施,
            //RectificationDescription = model.RectificationDescription//整改描述,
            //ActualTime = model.ActualTime//实际完成时间,
            //Acceptancer = model.Acceptancer//指定验收人,
            //ApprovalResult = model.ApprovalResult//验收意见,
            //AppointDepartment = model.AppointDepartment//验收部门,
            //AppointPerson = model.AppointPerson//验收用户,
            //AppointTime = model.AppointTime//验收时间,
            //Status = model.Status//状态(保存/提交),
            //Schedule = model.Schedule//隐患进度(/待审批/已生效/审批退回/验收通过/验收退回),
            //CreateFactory = model.CreateFactory//隶属工厂,
            //CreateDept = model.CreateDept//,
            //UpdateDept = model.UpdateDept//,
            //};
            return loadPageOffsetModel;
        }


        public async Task<IPageModel<YH_StandingBookDto>> GetList(PagingModel<YH_StandingBookDto> pagingQueryModel)
        {
            var loadPageOffsetModel = GetLoadPageOffsetMode(pagingQueryModel);
            return await base.LoadPageOffsetAsync(loadPageOffsetModel);
        }


        /// <summary>
        /// 修改隐患进度
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<bool> UpdateaSchedule(YH_StandingBookDto dto)
        {
            var entity = await _repository.Set.FirstOrDefaultAsync(a => a.Id == dto.Id);
            entity.Schedule = dto.Schedule;
            entity.ApprovalResult = dto.ApprovalResult;
            await _repository.SaveAsync();
            return true;
        }


        /// <summary>
        /// 整改描述
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<bool> UpdateaRectificationDescription(YH_StandingBookDto dto)
        {
            var entity = await _repository.Set.FirstOrDefaultAsync(a => a.Id == dto.Id);
            entity.RectificationDescription = dto.RectificationDescription;
            await _repository.SaveAsync();
            return true;
        }



        public async Task<string> Export(PagingModel<YH_StandingBookDto> pagingQueryModel)
        {
            var loadPageOffsetModel = GetLoadPageOffsetMode(pagingQueryModel);
            var DataList = await this.ExportDataAsync(loadPageOffsetModel);
            var excelData = DataList.Select((model, index) => new
            {
                Index = index + 1,
                Index_title="序号",
                model.StandingBookNo,
                StandingBookNo_title = "隐患治理编号",
                model.RiskRegionText,
                RiskRegionText_title = "隐患区域",
                model.RiskPositionText,
                RiskPositionText_title = "隐患位置",
                model.OrganizationTypeText,
                OrganizationTypeText_title = "组织级别",
                model.DiscoveryTime,
                DiscoveryTime_title = "检查时间",
                model.InspectTypeText,
                InspectTypeText_title = "排查类别",
                model.RiskDescription,
                RiskDescription_title = "隐患描述",
                model.RiskTypeText,
                RiskTypeText_title = "隐患分类",
                model.RiskLevelText,
                RiskLevelText_title = "隐患级别",
                model.RectificationCase,
                RectificationCase_title = "整改目标或方案",
                model.RectificationFund,
                RectificationFund_title = "整改资金（元）",
                model.RectificationLeadingName,
                RectificationLeadingName_title = "整改负责人",
                model.DepartmentName,
                DepartmentName_title = "整改责任部门",
                model.PlanTime,
                PlanTime_title = "计划完成时间",
                model.CurrentPlan,
                CurrentPlan_title = "当前控制措施",
                model.HaveContingencyPlan,
                HaveContingencyPlan_title = "是否制定应急预案",
                model.RectificationerName,
                RectificationerName_title = "整改人",
                model.ActualTime,
                ActualTime_title = "实际完成时间",
                model.AcceptancerName,
                AcceptancerName_title = "验收人",
                model.AppointTime,
                AppointTime_title = "验收时间",
                model.ApprovalResult,
                ApprovalResult_title = "验收意见",
                model.StateText,
                StateText_title = "状态"
            }).ToList();
            return _excelHelp.Create(excelData);
        }
    }

}







